﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Hope.Gallery.Business
{
    public class BL
    {
        private HopeGalleryEntities ctx;

        public BL()
        {
            ctx = new HopeGalleryEntities();
        }

        #region Album methods

        /// <summary>
        /// Get all albums
        /// </summary>
        /// <returns></returns>
        public List<Business.Album> GetAlbums()
        {
            return ctx.Albums
                .Include("AlbumDetails")
                .OrderByDescending(a => a.AddedDate)
                .ToList();
        }


        /// <summary>
        /// Get album by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Business.Album GetAlbumById(int id)
        {
            return ctx.Albums
                .Include("AlbumDetails")
                .FirstOrDefault(a => a.Id == id);
        }



        /// <summary>
        /// Add new album
        /// </summary>
        /// <param name="album"></param>
        public void AddAlbum(Models.Album album)
        {
            Business.Album newAlbum = new Album
            {
                Title = album.Title,
                Description = album.Description,
                AddedDate = DateTime.Now
            };

            ctx.Albums.AddObject(newAlbum);
        }

        /// <summary>
        /// Delete album
        /// </summary>
        /// <param name="idAlbum"></param>
        public void DeleteAlbum(int idAlbum)
        {
            var album = ctx.Albums
                .Where(a => a.Id == idAlbum)
                .FirstOrDefault();

            if (album != null)
            {
                ctx.Albums.DeleteObject(album);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="albumId"></param>
        /// <param name="fileName"></param>
        public void AddAlbumDetail(int albumId, string fileName)
        {
            var album = ctx.Albums
                .Include("AlbumDetails")
                .Where(a => a.Id == albumId).FirstOrDefault();

            if (album != null)
            {

                var existingDetail = album.AlbumDetails
                    .Where(d => d.Filename == fileName)
                    .FirstOrDefault();

                if (existingDetail == null)
                {
                    Business.AlbumDetail ad = new AlbumDetail();
                    ad.AlbumId = albumId;
                    ad.Filename = fileName;

                    ctx.AlbumDetails.AddObject(ad);
                }
            }
        }

        #endregion  
     
        /// <summary>
        /// Save changes
        /// </summary>
        public void SaveChanges()
        {
            ctx.SaveChanges();
        }
    }
}